package com.andengine.editor.factories;

import com.andengine.editor.textureregioneditor.TextureRegion;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.ByteBufferInput;
import com.esotericsoftware.kryo.io.ByteBufferOutput;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.swingson.exceptions.ErrorMessageException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author sad
 */
public class TextureRegionFactory {

    private static final String spriteDir = "D:/temp/sprites/";
    private static final TextureRegionFactory instance = new TextureRegionFactory();
    private static final String spriteFileExtension = ".trgn";

    public static TextureRegionFactory get() {
        return instance;
    }

    private TextureRegionFactory() {
    }

    public void save(String spriteName, TextureRegion sprite) {
        Kryo kryo = new Kryo();
        try (Output output = new ByteBufferOutput(new GZIPOutputStream(new FileOutputStream(new File(spriteDir, spriteName + spriteFileExtension))))) {
            kryo.writeObject(output, sprite);
        } catch (IOException ex) {
            throw new ErrorMessageException(ex.getMessage());
        }
    }

    public TextureRegion read(String spriteName) {
        Kryo kryo = new Kryo();
        try (Input input = new ByteBufferInput(new GZIPInputStream(new FileInputStream(new File(spriteDir, spriteName + spriteFileExtension))))) {
            TextureRegion sprite = kryo.readObject(input, TextureRegion.class);
            return sprite;
        } catch (IOException ex) {
            throw new ErrorMessageException(ex.getMessage());
        }
    }
}
